package com.example.backend.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.backend.common.Result;
import com.example.backend.entity.Program;
import com.example.backend.entity.VoteRecord;
import com.example.backend.mapper.ProgramMapper;
import com.example.backend.mapper.VoteRecordMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/program")
public class ProgramController {
    @Value("${server.port}")
    private String port;

    private static final String ip = "http://localhost";
    @Resource
    ProgramMapper programMapper;

    @Resource
    VoteRecordMapper voteRecordMapper;


    @PostMapping("/new")
    public Result<?> new_program(@RequestBody Map<String,Object> data) throws IOException {
        String file = (String) data.get("file");
        Integer parentId = Integer.parseInt((String) data.get("parentId"));
        String name = (String) data.get("name");
        String description = (String) data.get("description");
        String userId = (String) data.get("userId");


        Program program  = new Program();
        String originalFilename =".html";
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/htmls/" + flag + originalFilename;  // 获取上传的路径
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        String url = ip + ":" + port + "/htmls/" + flag;
        program.setId(null);
        program.setPath(url);
        program.setCommited(true);
        program.setParentId(parentId);
        program.setName(name);
        program.setUserId(userId);
        program.setDescription(description);
        programMapper.insert(program);
        return Result.success();
    }

    @PostMapping("get_program")
    public Result<?> get_program(@RequestBody Program program) throws IOException {
        System.out.println(program);
//        System.out.println(program.getPath());
        String[] temp = program.getPath().split("/");
        String flag = temp[temp.length - 1];
        String basePath = System.getProperty("user.dir") + "/src/main/resources/htmls/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        String content = null;
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                content = FileUtil.readUtf8String(basePath + fileName);
            }
        } catch (Exception e) {
            System.out.println("HTML文件获取失败");
        }
        return Result.success(content);
    }

    @PostMapping("like")
    public Result<?> program_like(@RequestBody Map<String,Object> data) throws IOException {
        String userId = (String) data.get("userId");
        Integer programId = (Integer) data.get("programId");
        System.out.println("userId: "+userId);
        System.out.println("programId: "+programId);

        VoteRecord temp = voteRecordMapper.selectOne(Wrappers.<VoteRecord>lambdaQuery().eq(VoteRecord::getProgramId,programId).eq(VoteRecord::getUserId,userId));

        if (temp == null){
            Program program = programMapper.selectOne(Wrappers.<Program>lambdaQuery().eq(Program::getId,programId));
            Integer num = program.getVoteLike();
            System.out.println("num: "+num);
            num++;
            program.setVoteLike(num);
            programMapper.updateById(program);
            VoteRecord new_one = new VoteRecord();
            new_one.setProgramId(programId);
            new_one.setUserId(userId);
            new_one.setVoteResult(true);
            voteRecordMapper.insert(new_one);
        }else {
            return Result.error("-1","已投过票");
        }
        return Result.success();
    }

    @PostMapping("dislike")
    public Result<?> program_dislike(@RequestBody Map<String,Object> data) throws IOException {
        String userId = (String) data.get("userId");
        Integer programId = (Integer) data.get("programId");

        VoteRecord temp = voteRecordMapper.selectOne(Wrappers.<VoteRecord>lambdaQuery().eq(VoteRecord::getProgramId,programId).eq(VoteRecord::getUserId,userId));
        if (temp == null){
            Program program = programMapper.selectOne(Wrappers.<Program>lambdaQuery().eq(Program::getId,programId));
            Integer num = program.getVoteDislike();
            num++;
            program.setVoteDislike(num);
            programMapper.updateById(program);
            VoteRecord new_one = new VoteRecord();
            new_one.setProgramId(programId);
            new_one.setUserId(userId);
            new_one.setVoteResult(false);
            voteRecordMapper.insert(new_one);
        }else {
            return Result.error("-1","已投过票,请勿重复投票");
        }
        return Result.success();
    }
}
